package com.usbserial.scale.adapter;

import com.usbserial.core.UsbSerialDeviceInfo;

import java.util.regex.Pattern;

/**
 * 电子秤设备标识符
 * 用于识别和匹配特定的电子秤设备
 */
public class ScaleDeviceIdentifier {
    private final String manufacturer;      // 制造商名称
    private final String model;              // 型号
    private final String specification;      // 规格（可选）
    private final Integer vendorId;          // USB VID（可选）
    private final Integer productId;         // USB PID（可选）
    private final Integer deviceClass;       // USB 设备类型（可选）

    private ScaleDeviceIdentifier(Builder builder) {
        this.manufacturer = builder.manufacturer;
        this.model = builder.model;
        this.specification = builder.specification;
        this.vendorId = builder.vendorId;
        this.productId = builder.productId;
        this.deviceClass = builder.deviceClass;
    }

    /**
     * 匹配设备信息
     * 优先级：VID/PID > 制造商+型号 > 设备类型
     *
     * @param deviceInfo USB 设备信息
     * @return 是否匹配
     */
    public boolean matches(UsbSerialDeviceInfo deviceInfo) {
        if (deviceInfo == null) {
            return false;
        }

        // 1. 优先匹配 VID/PID
        if (vendorId != null && productId != null) {
            boolean vidMatch = deviceInfo.getVendorId() == vendorId;
            boolean pidMatch = deviceInfo.getProductId() == productId;
            return vidMatch && pidMatch;
        }

        // 2. 匹配制造商和型号（支持正则表达式）
        if (manufacturer != null || model != null) {
            boolean manufacturerMatch = matchesString(
                deviceInfo.getManufacturerName(),
                manufacturer
            );
            boolean modelMatch = matchesString(
                deviceInfo.getProductName(),
                model
            );

            // 两者都指定时，都需要匹配
            if (manufacturer != null && model != null) {
                return manufacturerMatch && modelMatch;
            }
            // 只指定一个时，匹配那一个即可
            return manufacturerMatch || modelMatch;
        }

        // 3. 匹配设备类型
        if (deviceClass != null) {
            // 设备类型匹配逻辑（需要具体实现）
            // 这里简化处理，实际可能需要更复杂的逻辑
            return true;
        }

        return false;
    }

    /**
     * 字符串匹配（支持正则表达式）
     */
    private boolean matchesString(String actual, String pattern) {
        if (pattern == null) {
            return true;  // 未指定模式，视为匹配
        }
        if (actual == null) {
            return false;
        }

        // 支持正则表达式匹配
        try {
            return Pattern.matches(pattern, actual);
        } catch (Exception e) {
            // 正则表达式无效时，使用精确匹配
            return actual.equalsIgnoreCase(pattern);
        }
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public String getModel() {
        return model;
    }

    public String getSpecification() {
        return specification;
    }

    public Integer getVendorId() {
        return vendorId;
    }

    public Integer getProductId() {
        return productId;
    }

    public Integer getDeviceClass() {
        return deviceClass;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ScaleDeviceIdentifier{");
        if (manufacturer != null) sb.append("manufacturer='").append(manufacturer).append("', ");
        if (model != null) sb.append("model='").append(model).append("', ");
        if (specification != null) sb.append("specification='").append(specification).append("', ");
        if (vendorId != null) sb.append("vendorId=0x").append(Integer.toHexString(vendorId)).append(", ");
        if (productId != null) sb.append("productId=0x").append(Integer.toHexString(productId)).append(", ");
        if (deviceClass != null) sb.append("deviceClass=").append(deviceClass);
        sb.append("}");
        return sb.toString();
    }

    /**
     * 构建器
     */
    public static class Builder {
        private String manufacturer;
        private String model;
        private String specification;
        private Integer vendorId;
        private Integer productId;
        private Integer deviceClass;

        public Builder manufacturer(String manufacturer) {
            this.manufacturer = manufacturer;
            return this;
        }

        public Builder model(String model) {
            this.model = model;
            return this;
        }

        public Builder specification(String specification) {
            this.specification = specification;
            return this;
        }

        public Builder vendorId(int vendorId) {
            this.vendorId = vendorId;
            return this;
        }

        public Builder productId(int productId) {
            this.productId = productId;
            return this;
        }

        public Builder deviceClass(int deviceClass) {
            this.deviceClass = deviceClass;
            return this;
        }

        public ScaleDeviceIdentifier build() {
            return new ScaleDeviceIdentifier(this);
        }
    }
}
